using Microsoft.AspNetCore.Mvc;
using MVCDemoSoft2.Repository;
using MVCDemoSoft2.Models;
using System.Linq;
using MVCDemoSoft2.RequestParam;
using System.Collections.Generic;

namespace MVCDemoSoft2.Controllers
{
    public class BookController : Controller
    {
        private readonly IRepository<Book> _bookRep;
        private readonly IRepository<BookLibrary> _bookLibraryRep;

        public BookController(IRepository<Book> bookRep,IRepository<BookLibrary> bookLibraryRep)
        {
            _bookRep=bookRep;
            _bookLibraryRep=bookLibraryRep;
        }
        public IActionResult Index()
        {
            var hasAny=_bookLibraryRep.Table.FirstOrDefault();
            if(hasAny==null){
                _bookLibraryRep.Insert(new BookLibrary
                {
                    LibraryName="宇宙第一图书馆"
                });
            }

            // var bookRep = new EfRepository<Book>();
            IList<Book> books = _bookRep.Table.Where(x => x.IsDeleted == false).ToList();

            return View(books);
        }

        public IActionResult Query(BookQueryParam request)
        {
            // var bookRep = new EfRepository<Book>();
            var books = _bookRep.Table
            .Where(x => x.IsDeleted == false && x.BookName.Contains(request.Keywork))
            .ToList();

            return Json(books);
        }

        public IActionResult CreateOrEdit(int id)
        {
            if (id == 0)
            {
                return View();
            }
            else
            {
                // var bookRep = new EfRepository<Book>();
                var book = _bookRep.Table.Where(x => x.Id == id).FirstOrDefault();
                return View(book);
            }


        }
        public IActionResult Save(BookParam request)
        {
            // var bookRep = new EfRepository<Book>();

            if (request.Id == 0)
            {
                _bookRep.Insert(new Book
                {
                    BookName = request.BookName,
                    Author = request.Author,
                    Price = request.Price,
                    Publisher = request.Publisher,
                    ISBN = request.ISBN,
                    BookLibraryId = 1
                });
            }
            else
            {
                var book = _bookRep.Table.Where(x => x.Id == request.Id).FirstOrDefault();
                book.BookName = request.BookName;
                book.Author = request.Author;
                book.Price = request.Price;
                book.Publisher = request.Publisher;
                book.ISBN = request.ISBN;
                _bookRep.Update(book);
            }

            return Ok();
        }

        public IActionResult Delete(int id)
        {
            // var bookRep = new EfRepository<Book>();

            _bookRep.Delete(id);


            return RedirectToAction("Index");
        }
    }
}